/**
 * Check login state
 * Some middleware to help us ensure the user is authenticated.
 * https://github.com/vuejs/vue-router/issues/1048
 * https://jsfiddle.net/yezr0jjt/
 */

import store from '../store'
import router from '../router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getPageTitle } from '@/utils/common'

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

function cancelAjax() {
  window._axiosPromiseArr.forEach(item => {
    item.cancel()
  })
  window._axiosPromiseArr = []
}

const whiteList = ['/login'] // no redirect whitelist

export default app => {
  router.beforeEach(async (to, from, next) => {
    // log(to)
    cancelAjax()
    NProgress.start()
    document.title = getPageTitle(to.meta.title)

    const hasToken = store.state.user.token
    if (hasToken) {
      if (to.path === '/login') {
        // if is logged in, redirect to the home page
        next({
          path: '/'
        })
      } else {
        const hasGetUserInfo = store.state.user.roles && store.state.permission.routes.length > 0
        if (hasGetUserInfo) {
          next()
        } else {
          try {
            const accessRoutes = await store.dispatch('permission/generateRoutes')
            await store.commit('user/setRoles', true)
            // router.addRoutes(accessRoutes)
            accessRoutes.forEach(item => {
              router.addRoute(item)
            })

            next({
              ...to,
              replace: true
            })

          } catch (error) {
            await store.dispatch("user/logOut")
            Message.error(error || 'Has Error')
            next(`/login?redirect=${to.path}`)
          }

        }
      }
    } else {
      // log(whiteList.indexOf(to.path) !== -1)
      if (whiteList.indexOf(to.path) !== -1) {
        // in the free login whitelist, go directly
        next()
      } else {
        // other pages that do not have permission to access are redirected to the login page.
        next(`/login?redirect=${to.path}`)
      }
    }
  })

  router.afterEach(() => {
    // finish progress bar
    NProgress.done()
  })
}
